package com.manager.kudian.system.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.manager.kudian.common.persistence.HibernateDao;
import com.manager.kudian.common.service.BaseService;
import com.manager.kudian.system.dao.ManagerUserRoleDao;
import com.manager.kudian.system.entity.Role;
import com.manager.kudian.system.entity.ManagerUser;
import com.manager.kudian.system.entity.ManagerUserRole;

/**
 * 用户角色service
 * @author ty
 * @date 2015年1月14日
 */
@Service
@Transactional(readOnly = true)
public class ManagerUserRoleService extends BaseService<ManagerUserRole, Integer> {

	@Autowired
	private ManagerUserRoleDao managerUserRoleDao;

	@Override
	public HibernateDao<ManagerUserRole, Integer> getEntityDao() {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 添加修改用户角色
	 * 
	 * @param managerUserId
	 * @param oldList
	 * @param newList
	 */
	@Transactional(readOnly = false)
	public void updateUserRole(Integer managerUserId, List<Integer> oldList,List<Integer> newList) {
		// 是否删除
		for (int i = 0, j = oldList.size(); i < j; i++) {
			if (!newList.contains(oldList.get(i))) {
				managerUserRoleDao.deleteUR(managerUserId, oldList.get(i));
			}
		}

		// 是否添加
		for (int m = 0, n = newList.size(); m < n; m++) {
			if (!oldList.contains(newList.get(m))) {
				managerUserRoleDao.save(getUserRole(managerUserId, newList.get(m)));
			}
		}
	}

	/**
	 * 构建UserRole
	 * 
	 * @param managerUserId
	 * @param roleId
	 * @return UserRole
	 */
	private ManagerUserRole getUserRole(Integer managerUserId, Integer roleId) {
		ManagerUserRole ur = new ManagerUserRole();
		ur.setUser(new ManagerUser(managerUserId));
		ur.setRole(new Role(roleId));
		return ur;
	}

	/**
	 * 获取用户拥有角色id集合
	 * 
	 * @param managerUserId
	 * @return 结果集合
	 */
	public List<Integer> getRoleIdList(Integer managerUserId) {
		return managerUserRoleDao.findRoleIds(managerUserId);
	}

}
